﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Globalization;
using Microsoft.SilverlightMediaFramework.Utilities.Extensions;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net.Browser;
using Microsoft.Phone.Info;
using System.Text;
using System.Diagnostics.CodeAnalysis;
using System.Threading;

namespace YouTube
{
    public class Converter
    {

    }
    public class TimeSpanValueConverter : IValueConverter
    {
        // Methods
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return ((value is TimeSpan) ? ((TimeSpan)value).Format("{1:D2}:{2:D2}") : string.Empty);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    public static class YouTubePrivateAPI
    {
        // Fields
        private const string DeveloperKey = "AI39si5UpiUVST1HVuGjk2i3cESvd6nyaEMPEyHhiJ8V3WnkuhuRZxJgpaD3ZcdB6doWlk4ELqlem-82CrupyExN-PO-SnyaNw";
        private static string deviceId = null;
        private const string DeviceIdFileName = "DeviceId.dat";
        private static byte[] deviceKey = null;
        private const string DeviceKeyFileName = "DeviceKey.dat";
        private static Action deviceRegistrationComplete;
        private static Exception deviceRegistrationError;
        private static byte[] requestBytes;
        private static IsolatedStorageFile store;

        // Methods
        public static void ClearDeviceIdAndKey()
        {
            deviceId = null;
            deviceKey = null;
            if (store == null)
            {
                store = IsolatedStorageFile.GetUserStoreForApplication();
            }
            try
            {
                if (store.FileExists("DeviceId.dat"))
                {
                    store.DeleteFile("DeviceId.dat");
                }
            }
            catch (Exception)
            {
            }
            try
            {
                if (store.FileExists("DeviceKey.dat"))
                {
                    store.DeleteFile("DeviceKey.dat");
                }
            }
            catch (Exception)
            {
            }
        }

        [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "False alarm")]
        private static byte[] DecryptDeviceKey(byte[] cypherTextBytes)
        {
            byte[] rgbIV = new byte[0x10];
            byte[] buffer2 = null;
            byte[] buffer3 = null;
            byte[] rgbKey = null;
            using (ProtectedResourceStream stream = new ProtectedResourceStream(@"Resource\config.dat", "AI39si5UpiUVST1HVuGjk2i3cESvd6nyaEMPEyHhiJ8V3WnkuhuRZxJgpaD3ZcdB6doWlk4ELqlem-82CrupyExN-PO-SnyaNw"))
            {
                byte[] buffer = new byte[0x80];
                int count = stream.Read(buffer, 0, buffer.Length);
                UTF8Encoding encoding = new UTF8Encoding();
                rgbKey = Convert.FromBase64String(encoding.GetString(buffer, 0, count));
            }
            using (Aes aes = new AesManaged())
            {
                using (ICryptoTransform transform = aes.CreateDecryptor(rgbKey, rgbIV))
                {
                    ICryptoTransform transform2 = aes.CreateDecryptor(rgbKey, rgbIV);
                    Array.Clear(rgbKey, 0, rgbKey.Length);
                    MemoryStream stream2 = null;
                    CryptoStream stream3 = null;
                    try
                    {
                        try
                        {
                            stream2 = new MemoryStream();
                            stream3 = new CryptoStream(stream2, transform, CryptoStreamMode.Write);
                            stream3.Write(cypherTextBytes, 0, cypherTextBytes.Length);
                            stream3.Flush();
                            try
                            {
                                stream3.Close();
                            }
                            catch (CryptographicException)
                            {
                            }
                            stream3 = null;
                            buffer2 = stream2.ToArray();
                            byte[] buffer6 = transform2.TransformFinalBlock(cypherTextBytes, 0x10, 0x10);
                            buffer3 = new byte[buffer2.Length + buffer6.Length];
                            for (int i = 0; i < buffer2.Length; i++)
                            {
                                buffer3[i] = buffer2[i];
                            }
                            for (int j = 0; j < buffer6.Length; j++)
                            {
                                buffer3[j + buffer2.Length] = buffer6[j];
                            }
                        }
                        catch (CryptographicException)
                        {
                            buffer3 = null;
                        }
                        return buffer3;
                    }
                    finally
                    {
                        try
                        {
                            if (stream2 != null)
                            {
                                stream2.Dispose();
                            }
                            if (stream3 != null)
                            {
                                stream3.Dispose();
                            }
                            if (transform2 != null)
                            {
                                transform2.Dispose();
                            }
                        }
                        catch (CryptographicException)
                        {
                        }
                    }
                    return buffer3;
                }
            }
        }

        public static void EnsureDeviceRegistered(Action callback)
        {
            LoadDeviceIdKeyFromIsolatedStorage(out deviceId, out deviceKey);
            if (DeviceRegistered)
            {
                if (callback != null)
                {
                    callback();
                }
            }
            else
            {
                RegisterDevice(callback);
            }
        }

        private static void LoadDeviceIdKeyFromIsolatedStorage(out string oldDeviceId, out byte[] oldDeviceKey)
        {
            oldDeviceId = null;
            oldDeviceKey = null;
            if (store == null)
            {
                store = IsolatedStorageFile.GetUserStoreForApplication();
            }
            if (store.FileExists("DeviceId.dat") && store.FileExists("DeviceKey.dat"))
            {
                try
                {
                    IsolatedStorageFileStream stream = null;

                        stream = new IsolatedStorageFileStream("DeviceId.dat", FileMode.Open, FileAccess.Read, store);
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            stream = null;
                            oldDeviceId = reader.ReadToEnd();
                        }
                   
                    using (ProtectedStream stream2 = new ProtectedStream(store, "DeviceKey.dat", FileAccess.Read))
                    {
                        byte[] buffer = new byte[0x80];
                        int length = stream2.Read(buffer, 0, buffer.Length);
                        if (length > 0)
                        {
                            deviceKey = new byte[length];
                            Array.Copy(buffer, deviceKey, length);
                        }
                    }
                }
                catch (Exception)
                {
                }
            }
        }

        private static void RegisterDevice(Action callback)
        {
            HttpWebRequest request = null;
            deviceRegistrationComplete = callback;
            string uriString = "http://www.google.com/youtube/accounts/registerDevice";
            request = WebRequestCreator.ClientHttp.Create(new Uri(uriString)) as HttpWebRequest;
            request.Method=("POST");
            byte[] inArray = DeviceExtendedProperties.GetValue("DeviceUniqueId") as byte[];
            string str2 = Convert.ToBase64String(inArray);
            string s = "developer=AI39si7Smp2fnF3RgL5bjn2N3VHGz2ciTUu7lLCFynzfUvNSyDuL554CXR1PUdMUj9TdBfe9jyYplofF4VlPGVEb85iKwEuFqA" + str2;
            requestBytes = new UTF8Encoding().GetBytes(s);
            int length = requestBytes.Length;
            request.Headers["ContentLength"]= length.ToString(CultureInfo.InvariantCulture);
            request.ContentType=("application/x-www-form-urlencoded");
            try
            {
                request.BeginGetRequestStream(new AsyncCallback(YouTubePrivateAPI.RegisterDeviceGetRequestStreamCallback), request);
                return;
            }
            catch (WebException exception)
            {
                deviceRegistrationError = exception;
            }
            catch (InvalidOperationException exception2)
            {
                deviceRegistrationError = exception2;
            }
            catch (NotSupportedException exception3)
            {
                deviceRegistrationError = exception3;
            }
          //  RegisterDeviceExecuteCallback();
        }

        private static void RegisterDeviceExecuteCallback()
        {
            if (deviceRegistrationComplete != null)
            {
                deviceRegistrationComplete();
                deviceRegistrationComplete = null;
            }
        }
        

        private static void RegisterDeviceGetRequestStreamCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest asyncState = (HttpWebRequest)asynchronousResult.AsyncState;
            Stream stream = null;
            try
            {
                stream = asyncState.EndGetRequestStream(asynchronousResult);
                stream.Write(requestBytes, 0, requestBytes.Length);
                stream.Close();
                stream = null;
                asyncState.BeginGetResponse(new AsyncCallback(YouTubePrivateAPI.RegisterDeviceGetResponseCallback), asyncState);
                return;
            }
            catch (WebException exception)
            {
                deviceRegistrationError = exception;
            }
            catch (ArgumentNullException exception2)
            {
                deviceRegistrationError = exception2;
            }
            catch (ArgumentException exception3)
            {
                deviceRegistrationError = exception3;
            }
            catch (IOException exception4)
            {
                deviceRegistrationError = exception4;
            }
            catch (InvalidOperationException exception5)
            {
                deviceRegistrationError = exception5;
            }
            if (stream != null)
            {
                stream.Close();
            }
         //   RegisterDeviceExecuteCallback();
        }

        private static void RegisterDeviceGetResponseCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest asyncState = (HttpWebRequest)asynchronousResult.AsyncState;
            HttpWebResponse response = null;
            Stream responseStream = null;
            StreamReader reader = null;
            string str = null;
            try
            {
                response = (HttpWebResponse)asyncState.EndGetResponse(asynchronousResult);
            }
            catch (WebException exception)
            {
                deviceRegistrationError = exception;
                goto Label_0092;
            }
            catch (ArgumentNullException exception2)
            {
                deviceRegistrationError = exception2;
                goto Label_0092;
            }
            catch (ArgumentException exception3)
            {
                deviceRegistrationError = exception3;
                goto Label_0092;
            }
            catch (InvalidOperationException exception4)
            {
                deviceRegistrationError = exception4;
                goto Label_0092;
            }
            try
            {
                responseStream = response.GetResponseStream();
                using (reader = new StreamReader(responseStream))
                {
                    responseStream = null;
                    str = reader.ReadToEnd();
                }
            }
            catch (IOException exception5)
            {
                deviceRegistrationError = exception5;
            }
            finally
            {
                if (responseStream != null)
                {
                    responseStream.Close();
                }
            }
        Label_0092:
            if (response != null)
            {
                response.Close();
            }
            if (!string.IsNullOrEmpty(str))
            {
                SaveDeviceKey(str);
            }
            RegisterDeviceExecuteCallback();
        }

        private static void SaveDeviceIdKeyToIsolatedStorage(string newDeviceId, byte[] newDeviceKey)
        {
            if (store == null)
            {
                store = IsolatedStorageFile.GetUserStoreForApplication();
            }
            try
            {
                IsolatedStorageFileStream stream = null;
                
                    stream = new IsolatedStorageFileStream("DeviceId.dat", FileMode.Create, FileAccess.Write, store);
                    using (StreamWriter writer = new StreamWriter(stream))
                    {
                        stream = null;
                        writer.Write(newDeviceId);
                    }
               
                if (store.FileExists("DeviceKey.dat"))
                {
                    store.DeleteFile("DeviceKey.dat");
                }
                using (ProtectedStream stream2 = new ProtectedStream(store, "DeviceKey.dat", FileAccess.Write))
                {
                    stream2.Write(newDeviceKey, 0, newDeviceKey.Length);
                }
            }
            catch (Exception)
            {
            }
        }

        private static void SaveDeviceKey(string wencryptedResponse)
        {
            RegexOptions options = RegexOptions.CultureInvariant | RegexOptions.Compiled | RegexOptions.Multiline;
            MatchCollection matchs = new Regex("^(?<Key>[^=]*)=(?<Value>.*)$", options).Matches(wencryptedResponse);
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            foreach (Match match in matchs)
            {
                dictionary.Add(match.Groups["Key"].Value, match.Groups["Value"].Value);
            }
            deviceId = dictionary["DeviceId"];
            string str = dictionary["DeviceKey"];
            if (string.IsNullOrEmpty(deviceId) || string.IsNullOrEmpty(str))
            {
                deviceRegistrationError = new WebException("Device registration failed");
            }
            else
            {
                deviceKey = DecryptDeviceKey(Convert.FromBase64String(str));
                if ((deviceKey == null) || (deviceKey.Length == 0))
                {
                    deviceRegistrationError = new WebException("Device registration failed");
                }
                else
                {
                    SaveDeviceIdKeyToIsolatedStorage(deviceId, deviceKey);
                }
            }
        }

        public static string Signature(string path)
        {
            if (deviceKey == null)

            {
                LoadDeviceIdKeyFromIsolatedStorage(out deviceId, out deviceKey);
            }

                using (HMACSHA1 hmacsha = new HMACSHA1(deviceKey))
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(path);
                    string str = Convert.ToBase64String(hmacsha.ComputeHash(bytes));
                    return ("device-id=\"" + deviceId + "\",data=\"" + str + "\"");
                }
            
        }

        // Properties
        public static bool DeviceRegistered
        {
            get
            {
                return ((deviceId != null) && (deviceKey != null));
            }
        }

        public static Exception DeviceRegistrationError
        {
            get
            {
                return deviceRegistrationError;
            }
        }
    }
    public class ProtectedResourceStream : Stream
    {
        // Fields
        private const string ClassName = "ProtectedResourceStream";
        private bool disposed;
        private static readonly byte[] FileSignature = new byte[] { 0x52, 0x4a, 0x53, 0x53, 0x4a, 0x4a };
        private Aes mAes;
        private CryptoStream mEncryptedStream;
        private MemoryStream mMemoryStream;
        private string mRawKey;
        private static readonly byte[] OperatorList = new byte[] { 2, 0, 1, 0, 0, 2, 1, 2, 0, 1, 1, 2, 0, 2, 2, 1 };
        private static readonly byte[] Seed = new byte[] { 
        0x52, 100, 4, 0x1a, 240, 0x71, 0x5e, 0x4d, 0xfe, 190, 0x41, 0x16, 0x85, 0x4f, 0x11, 0x4f, 
        0xb3
     };

        // Methods
        public ProtectedResourceStream(string filename, string rawKey)
        {
            this.mRawKey = rawKey;
            this.InitializeForRead(filename);
        }

        private static byte[] AcquireKey(string rawKey)
        {
            Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(rawKey, GetSalt());
            return bytes.GetBytes(0x10);
        }

        protected override void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    if (this.mEncryptedStream != null)
                    {
                        this.mEncryptedStream.Dispose();
                        this.mEncryptedStream = null;
                    }
                    if (this.mMemoryStream != null)
                    {
                        this.mMemoryStream.Dispose();
                        this.mMemoryStream = null;
                    }
                    if (this.mAes != null)
                    {
                        this.mAes.Clear();
                        this.mAes = null;
                    }
                }
                this.disposed = true;
            }
            base.Dispose(disposing);
        }

        public override void Flush()
        {
            throw new NotSupportedException();
        }

        private static byte[] GetSalt()
        {
            byte[] buffer = new byte[Seed.Length - 1];
            int index = 0;
            byte num2 = Seed[0];
            for (int i = 0; i < buffer.Length; i++)
            {
                buffer[i] = Seed[i + 1];
                switch (OperatorList[index])
                {
                    case 0:
                        buffer[i] = (byte)(buffer[i] ^ num2);
                        break;

                    case 1:
                        {
                            int num4 = buffer[i] << (num2 & 7);
                            buffer[i] = (byte)((num4 | (num4 >> 8)) & 0xff);
                            break;
                        }
                    case 2:
                        {
                            int num5 = (buffer[i] * 0x100) >> (num2 & 7);
                            buffer[i] = (byte)((num5 | (num5 >> 8)) & 0xff);
                            break;
                        }
                    default:
                        throw new FormatException("Bad key transform.");
                }
                num2 = Seed[i + 1];
                if (++index >= OperatorList.Length)
                {
                    index = 0;
                }
            }
            return buffer;
        }

        private void InitializeForRead(string filename)
        {
            byte[] buffer = null;
            Stream input = null;
            using (input = Application.GetResourceStream(new Uri(filename, UriKind.Relative)).Stream)
            {
                using (BinaryReader reader = new BinaryReader(input))
                {
                    input = null;
                    buffer = reader.ReadBytes((int)reader.BaseStream.Length);
                }
            }
            this.mMemoryStream = new MemoryStream(buffer);
            byte[] buffer2 = new byte[FileSignature.Length];
            if (this.mMemoryStream.Read(buffer2, 0, FileSignature.Length) != FileSignature.Length)
            {
                this.mMemoryStream.Close();
                throw new UnauthorizedAccessException();
            }
            for (int i = 0; i < FileSignature.Length; i++)
            {
                if (FileSignature[i] != buffer2[i])
                {
                    this.mMemoryStream.Close();
                    throw new UnauthorizedAccessException();
                }
            }
            byte[] buffer3 = new byte[4];
            if (this.mMemoryStream.Read(buffer3, 0, buffer3.Length) != buffer3.Length)
            {
                throw new UnauthorizedAccessException();
            }
            byte[] buffer4 = new byte[BitConverter.ToInt32(buffer3, 0)];
            if (this.mMemoryStream.Read(buffer4, 0, buffer4.Length) != buffer4.Length)
            {
                throw new UnauthorizedAccessException();
            }
            if (this.mAes == null)
            {
                this.mAes = new AesManaged();
            }
            this.mAes.IV = buffer4;
            this.mAes.Key = AcquireKey(this.mRawKey);
            this.mEncryptedStream = new CryptoStream(this.mMemoryStream, this.mAes.CreateDecryptor(), CryptoStreamMode.Read);
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            if (this.disposed)
            {
                throw new ObjectDisposedException("ProtectedResourceStream");
            }
            return this.mEncryptedStream.Read(buffer, offset, count);
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new NotSupportedException();
        }

        public override void SetLength(long value)
        {
            throw new NotSupportedException();
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            throw new NotSupportedException();
        }

        // Properties
        public override bool CanRead
        {
            get
            {
                if (this.disposed)
                {
                    throw new ObjectDisposedException("ProtectedResourceStream");
                }
                return this.mEncryptedStream.CanRead;
            }
        }

        public override bool CanSeek
        {
            get
            {
                if (this.disposed)
                {
                    throw new ObjectDisposedException("ProtectedResourceStream");
                }
                return this.mEncryptedStream.CanSeek;
            }
        }

        public override bool CanWrite
        {
            get
            {
                if (this.disposed)
                {
                    throw new ObjectDisposedException("ProtectedResourceStream");
                }
                return this.mEncryptedStream.CanWrite;
            }
        }

        public override long Length
        {
            get
            {
                throw new NotSupportedException();
            }
        }

        public override long Position
        {
            get
            {
                throw new NotSupportedException();
            }
            set
            {
                throw new NotSupportedException();
            }
        }
    }
    public class ProtectedStream : Stream
    {
        // Fields
        private const string ClassName = "ProtectedStream";
        private bool disposed;
        private static readonly byte[] FileSignature = new byte[] { 0x52, 0x4a, 0x53, 0x53, 0x4a, 0x4a };
        private Aes mAes;
        private Stream mEncryptedStream;
        private IsolatedStorageFileStream mIsoStream;
        private static readonly byte[] OperatorList = new byte[] { 2, 0, 1, 0, 0, 2, 1, 2, 0, 1, 1, 2, 0, 2, 2, 1 };
        private static readonly byte[] Seed = new byte[] { 
        0x52, 100, 4, 0x1a, 240, 0x71, 0x5e, 0x4d, 0xfe, 190, 0x41, 0x16, 0x85, 0x4f, 0x11, 0x4f, 
        0xb3
     };

        // Methods
        public ProtectedStream(IsolatedStorageFile store, string filename, FileAccess readOrWrite)
        {
            switch (readOrWrite)
            {
                case FileAccess.Read:
                    this.InitializeForRead(store, filename);
                    return;

                case FileAccess.Write:
                    this.InitializeForWrite(store, filename);
                    return;
            }
            throw new ArgumentException("Only read OR write access is allowed.");
        }

        private static byte[] AcquireKey()
        {
            object obj2;
            if (!DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out obj2))
            {
                throw new UnauthorizedAccessException("WMAppManifest must contain: <Capability Name=\"ID_CAP_IDENTITY_DEVICE\" />");
            }
            byte[] buffer = (byte[])obj2;
            StringBuilder builder = new StringBuilder();
            foreach (byte num in buffer)
            {
                builder.Append(num.ToString("x", CultureInfo.InvariantCulture));
            }
            Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(builder.ToString(), GetSalt());
            return bytes.GetBytes(0x10);
        }

        protected override void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    if (this.mEncryptedStream != null)
                    {
                        this.mEncryptedStream.Dispose();
                        this.mEncryptedStream = null;
                    }
                    if (this.mIsoStream != null)
                    {
                        this.mIsoStream.Dispose();
                        this.mIsoStream = null;
                    }
                    if (this.mAes != null)
                    {
                        this.mAes.Clear();
                        this.mAes = null;
                    }
                }
                this.disposed = true;
            }
            base.Dispose(disposing);
        }

        public override void Flush()
        {
            if (this.disposed)
            {
                throw new ObjectDisposedException("ProtectedStream");
            }
            this.mEncryptedStream.Flush();
        }

        private static byte[] GetSalt()
        {
            byte[] buffer = new byte[Seed.Length - 1];
            int index = 0;
            byte num2 = Seed[0];
            for (int i = 0; i < buffer.Length; i++)
            {
                buffer[i] = Seed[i + 1];
                switch (OperatorList[index])
                {
                    case 0:
                        buffer[i] = (byte)(buffer[i] ^ num2);
                        break;

                    case 1:
                        {
                            int num4 = buffer[i] << (num2 & 7);
                            buffer[i] = (byte)((num4 | (num4 >> 8)) & 0xff);
                            break;
                        }
                    case 2:
                        {
                            int num5 = (buffer[i] * 0x100) >> (num2 & 7);
                            buffer[i] = (byte)((num5 | (num5 >> 8)) & 0xff);
                            break;
                        }
                    default:
                        throw new FormatException("Bad key transform.");
                }
                num2 = Seed[i + 1];
                if (++index >= OperatorList.Length)
                {
                    index = 0;
                }
            }
            return buffer;
        }

        private void InitializeForRead(IsolatedStorageFile store, string filename)
        {
            byte[] buffer = new byte[FileSignature.Length];
            this.mIsoStream = new IsolatedStorageFileStream(filename, FileMode.Open, FileAccess.Read, store);
            if (this.mIsoStream.Read(buffer, 0, FileSignature.Length) != FileSignature.Length)
            {
                this.mIsoStream.Close();
                throw new UnauthorizedAccessException();
            }
            for (int i = 0; i < FileSignature.Length; i++)
            {
                if (FileSignature[i] != buffer[i])
                {
                    this.mIsoStream.Close();
                    throw new UnauthorizedAccessException();
                }
            }
            byte[] buffer2 = new byte[4];
            if (this.mIsoStream.Read(buffer2, 0, buffer2.Length) != buffer2.Length)
            {
                throw new UnauthorizedAccessException();
            }
            byte[] buffer3 = new byte[BitConverter.ToInt32(buffer2, 0)];
            if (this.mIsoStream.Read(buffer3, 0, buffer3.Length) != buffer3.Length)
            {
                throw new UnauthorizedAccessException();
            }
            if (this.mAes == null)
            {
                this.mAes = new AesManaged();
            }
            this.mAes.IV = buffer3;
            this.mAes.Key = AcquireKey();
            this.mEncryptedStream = new CryptoStream(this.mIsoStream, this.mAes.CreateDecryptor(), CryptoStreamMode.Read);
        }

        private void InitializeForWrite(IsolatedStorageFile store, string filename)
        {
            this.mIsoStream = new IsolatedStorageFileStream(filename, FileMode.CreateNew, FileAccess.Write, store);
            if (this.mAes == null)
            {
                this.mAes = new AesManaged();
            }
            this.mIsoStream.Write(FileSignature, 0, FileSignature.Length);
            this.mIsoStream.Write(BitConverter.GetBytes(this.mAes.IV.Length), 0, 4);
            this.mIsoStream.Write(this.mAes.IV, 0, this.mAes.IV.Length);
            this.mAes.Key = AcquireKey();
            this.mEncryptedStream = new CryptoStream(this.mIsoStream, this.mAes.CreateEncryptor(), CryptoStreamMode.Write);
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            if (this.disposed)
            {
                throw new ObjectDisposedException("ProtectedStream");
            }
            return this.mEncryptedStream.Read(buffer, offset, count);
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new NotSupportedException();
        }

        public override void SetLength(long value)
        {
            throw new NotSupportedException();
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            if (this.disposed)
            {
                throw new ObjectDisposedException("ProtectedStream");
            }
            this.mEncryptedStream.Write(buffer, offset, count);
        }

        // Properties
        public override bool CanRead
        {
            get
            {
                if (this.disposed)
                {
                    throw new ObjectDisposedException("ProtectedStream");
                }
                return this.mEncryptedStream.CanRead;
            }
        }

        public override bool CanSeek
        {
            get
            {
                if (this.disposed)
                {
                    throw new ObjectDisposedException("ProtectedStream");
                }
                return this.mEncryptedStream.CanSeek;
            }
        }

        public override bool CanWrite
        {
            get
            {
                if (this.disposed)
                {
                    throw new ObjectDisposedException("ProtectedStream");
                }
                return this.mEncryptedStream.CanWrite;
            }
        }

        public override long Length
        {
            get
            {
                throw new NotSupportedException();
            }
        }

        public override long Position
        {
            get
            {
                throw new NotSupportedException();
            }
            set
            {
                throw new NotSupportedException();
            }
        }
    }




}
